import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/site/site_device_manager/site_device_manager_controller.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_controller.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';

import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/toast_utils.dart';

import 'base_basic_model.dart';

class BaseBasicController extends GetxController {
  DeviceServices services = Get.put(DeviceServices());

  DeviceModel? device;

  Map<String, dynamic>? deviceJson;

  Map<String, dynamic> get paramConfig {
    var thirdSiteId = deviceJson?['config']?['thirdSiteId'];
    deviceJson?['config']?['thirdSiteId'] = thirdSiteId?.toString();
    return deviceJson?['config'] ?? {};
  }

  String title = '';

  List<SiteListModel> sites = [];
  List<DeviceInfoItem> get infos => device == null
      ? []
      : [
          DeviceInfoItem(
              label: ResKey.deviceName.tr,
              value: device?.name ?? ' ',
              extraText: device?.forShort,
              type: FieldType.input,
              valueOnchange: (String str) {
                device?.name = str;
                update();
              }),
          DeviceInfoItem(
              label: ResKey.deviceType.tr,
              value: device?.productTypeName ?? ' ',
              type: FieldType.text),
          if (device?.masterSlaveMode != null)
            DeviceInfoItem(
                label: ResKey.deviceMasterSlaveSystemName.tr, //主从系统名称
                value: device?.masterSlaveSystemName ?? ' ',
                type: device?.masterSlaveMode == MasterSlaveModeType.master
                    ? FieldType.input
                    : FieldType.text,
                valueOnchange: (String str) {
                  device?.masterSlaveSystemName = str;
                  update();
                }),
          DeviceInfoItem(
            label: ResKey.siteName.tr,
            value: device?.siteName ?? ' ',
            type: FieldType.text,
          ),
          // DeviceInfoItem(
          //     label: ResKey.owningSubsystem.tr,
          //     value: device?.subsystemName ?? ' ',
          //     type: FieldType.text),
          DeviceInfoItem(
              label: 'SN ${ResKey.deviceSerialNumber.tr}',
              value: device?.sn ?? ' ',
              type: FieldType.text,
              valueOnchange: (String str) {
                device?.sn = str;
                update();
              }),
          DeviceInfoItem(
              label: ResKey.productModel.tr,
              value: device?.model ?? ' ',
              type: FieldType.text),
          DeviceInfoItem(
              label: ResKey.deviceSoftwareVersion.tr,
              value: device?.softVersion ?? ' ',
              type: FieldType.text),
        ];

  int? deviceId;

  bool isEdit = false;

  // 弹出列表
  List<PopupMenuItem> popList = [];

  PopupMenuItem? generatePopItem(Widget icon, String title, value,
      {String? permission}) {
    var isPassPermission =
        permission == null ? true : FuncUtils.isPassAuthority([permission]);

    return isPassPermission
        ? PopupMenuItem(
            value: value,
            enabled: false,
            child: Row(
              children: [
                icon,
                Gaps.hGap10,
                Text(
                  title,
                  style: TextStyles.f14,
                ),
              ],
            ),
          )
        : null;
  }

  // 获取设备信息
  Future getDeviceInfo({bool showLoading = true}) =>
      Configs.httpClient.requestWithLoading(() async {
        var json = await services.getDeviceInfo({'deviceId': deviceId});
        if (json['config'] != null) {
          json['config'] = jsonDecode(json['config']);
        }
        deviceJson = json;

        /// 导航栏弹出层初始化
        popList.clear();

        var pop = generatePopItem(
          Image.asset(ImageAssets.siteSettingBaseInfoEdit,
              width: 20.w, fit: BoxFit.fitWidth),
          ResKey.audit.tr,
          0,
          permission: PermissionConstant.deviceDetailBasicInfoEdit,
        );
        if (pop != null) {
          popList.add(pop);
        }

        device = DeviceModel.fromJson(json);
        if (device?.masterSlaveMode != MasterSlaveModeType.vice &&
            device?.paramConfigType != null &&
            device?.paramConfigType != 0 &&
            device?.paramConfigType != 6) {
          popList.add(pop!);
        }
        if (device?.productConfigType != null) {
          var pop = generatePopItem(
              Image.asset(
                ImageAssets.iconDeviceSetting,
                fit: BoxFit.fitWidth,
                width: 20.w,
              ),
              ResKey.deviceSets.tr,
              2);

          popList.add(pop!);
        }
        title = device?.name ?? '';
        update();
      }, showLoading: showLoading);

  // 取消修改
  void cancelEdit() {
    isEdit = false;
    if (deviceJson != null) {
      device = DeviceModel.fromJson(deviceJson!);
    }
    update();
  }

  //去修改信息
  Future? toAudit() => Get.toNamed(RouterPath.editDevice, arguments: {
        'modelList': infos,
        'device': device,
      })?.then((value) {
        if (value == true) {
        } else {
          cancelEdit();
        }
      });

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    getDeviceInfo();
  }

  @override
  void dispose() {
    super.dispose();
  }
}
